package com.kaizeli.website.controller;

import com.kaizeli.website.pojo.dto.base.PageDTO;
import com.kaizeli.website.pojo.entity.ProjectBasicInfoDO;
import com.kaizeli.website.pojo.vo.ProjectBasicInfoVO;
import com.kaizeli.website.query.ProjectBasicInfoQuery;
import com.kaizeli.website.response.Result;
import com.kaizeli.website.service.ProjectBasicInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 项目基础信息管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/project-basic-infos")
@RequiredArgsConstructor
@Tag(name = "项目基础信息管理", description = "项目基础信息管理相关接口")
@SecurityRequirement(name = "Bearer Authentication")
public class ProjectBasicInfoController {
    
    private final ProjectBasicInfoService projectBasicInfoService;
    
    @Operation(summary = "分页查询项目列表", description = "支持按项目编号、名称、状态、客户、签约公司等条件分页查询项目信息")
    @GetMapping("/page")
    public Result<PageDTO<ProjectBasicInfoVO>> pageQuery(ProjectBasicInfoQuery query) {
        log.info("分页查询项目列表，查询条件：{}", query);
        PageDTO<ProjectBasicInfoVO> result = projectBasicInfoService.pageQuery(query);
        return Result.success(result);
    }
    
    @Operation(summary = "根据ID查询项目详情", description = "根据项目ID查询项目详细信息")
    @GetMapping("/{id}")
    public Result<ProjectBasicInfoVO> getById(
            @Parameter(description = "项目ID", required = true, example = "1")
            @PathVariable Long id) {
        log.info("根据ID查询项目详情，ID：{}", id);
        ProjectBasicInfoVO result = projectBasicInfoService.getById(id);
        return Result.success(result);
    }
    
    @Operation(summary = "根据项目编号查询项目", description = "根据项目唯一编号查询项目信息")
    @GetMapping("/code/{projectCode}")
    public Result<ProjectBasicInfoVO> getByProjectCode(
            @Parameter(description = "项目编号", required = true, example = "PROJ001")
            @PathVariable String projectCode) {
        log.info("根据项目编号查询项目，编号：{}", projectCode);
        ProjectBasicInfoVO result = projectBasicInfoService.getByProjectCode(projectCode);
        return Result.success(result);
    }
    
    @Operation(summary = "新增项目", description = "创建新的项目信息")
    @PostMapping
    public Result<Long> save(
            @Parameter(description = "项目信息", required = true)
            @RequestBody ProjectBasicInfoDO projectBasicInfoDO) {
        log.info("新增项目，项目信息：{}", projectBasicInfoDO);
        log.info("项目编号：{}", projectBasicInfoDO.getProjectCode());
        log.info("项目名称：{}", projectBasicInfoDO.getProjectName());
        log.info("项目预算：{}", projectBasicInfoDO.getProjectBudget());
        log.info("项目类型：{}", projectBasicInfoDO.getProjectType());
        log.info("客户ID：{}", projectBasicInfoDO.getCustomerId());
        log.info("签约公司ID：{}", projectBasicInfoDO.getContractCompanyId());
        log.info("项目经理ID：{}", projectBasicInfoDO.getManagerId());
        log.info("项目总监ID：{}", projectBasicInfoDO.getDirectorId());
        log.info("状态：{}", projectBasicInfoDO.getStatus());
        Long result = projectBasicInfoService.save(projectBasicInfoDO);
        return Result.success(result);
    }
    
    @Operation(summary = "更新项目信息", description = "根据ID更新项目信息")
    @PutMapping("/{id}")
    public Result<Boolean> update(
            @Parameter(description = "项目ID", required = true, example = "1")
            @PathVariable Long id,
            @Parameter(description = "更新的项目信息", required = true)
            @RequestBody ProjectBasicInfoDO projectBasicInfoDO) {
        log.info("更新项目信息，ID：{}，更新信息：{}", id, projectBasicInfoDO);
        projectBasicInfoDO.setId(id);
        Boolean result = projectBasicInfoService.update(projectBasicInfoDO);
        return Result.success(result);
    }
    
    @Operation(summary = "根据ID删除项目", description = "根据项目ID删除项目信息")
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteById(
            @Parameter(description = "项目ID", required = true, example = "1")
            @PathVariable Long id) {
        log.info("根据ID删除项目，ID：{}", id);
        Boolean result = projectBasicInfoService.deleteById(id);
        return Result.success(result);
    }
    
    @Operation(summary = "作废项目", description = "将项目状态设置为作废审批中，并同步更新关联的验收单和验收成员状态")
    @PutMapping("/{id}/void")
    public Result<Boolean> voidProject(
            @Parameter(description = "项目ID", required = true, example = "1")
            @PathVariable Long id) {
        log.info("作废项目，ID：{}", id);
        Boolean result = projectBasicInfoService.voidProject(id);
        return Result.success(result);
    }
    
    @Operation(summary = "根据客户ID查询项目列表", description = "根据客户ID查询该客户的所有项目")
    @GetMapping("/customer/{customerId}")
    public Result<List<ProjectBasicInfoVO>> listByCustomerId(
            @Parameter(description = "客户ID", required = true, example = "1")
            @PathVariable Long customerId) {
        log.info("根据客户ID查询项目列表，客户ID：{}", customerId);
        List<ProjectBasicInfoVO> result = projectBasicInfoService.listByCustomerId(customerId);
        return Result.success(result);
    }
    
    @Operation(summary = "根据签约公司ID查询项目列表", description = "根据签约公司ID查询该公司签约的所有项目")
    @GetMapping("/contract-company/{contractCompanyId}")
    public Result<List<ProjectBasicInfoVO>> listByContractCompanyId(
            @Parameter(description = "签约公司ID", required = true, example = "1")
            @PathVariable Long contractCompanyId) {
        log.info("根据签约公司ID查询项目列表，签约公司ID：{}", contractCompanyId);
        List<ProjectBasicInfoVO> result = projectBasicInfoService.listByContractCompanyId(contractCompanyId);
        return Result.success(result);
    }
    
    @Operation(summary = "根据项目状态查询项目列表", description = "根据项目状态查询项目列表")
    @GetMapping("/status/{status}")
    public Result<List<ProjectBasicInfoVO>> listByStatus(
            @Parameter(description = "项目状态", required = true, example = "in_progress")
            @PathVariable String status) {
        log.info("根据项目状态查询项目列表，状态：{}", status);
        List<ProjectBasicInfoVO> result = projectBasicInfoService.listByStatus(status);
        return Result.success(result);
    }
    
    @Operation(summary = "查询所有项目列表", description = "查询系统中所有项目信息")
    @GetMapping("/all")
    public Result<List<ProjectBasicInfoVO>> listAll() {
        log.info("查询所有项目列表");
        try {
            List<ProjectBasicInfoVO> result = projectBasicInfoService.listAll();
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询所有项目失败", e);
            return Result.error(500, "查询失败：" + e.getMessage());
        }
    }
    
    @Operation(summary = "测试数据库连接", description = "测试数据库连接和表结构（无需认证）")
    @GetMapping("/test-db")
    public Result<Map<String, Object>> testDatabase() {
        log.info("测试数据库连接");
        try {
            // 尝试查询表结构
            List<ProjectBasicInfoDO> list = projectBasicInfoService.testDatabase();
            Map<String, Object> result = new HashMap<>();
            result.put("tableExists", true);
            result.put("recordCount", list.size());
            result.put("message", "数据库连接正常，表结构正确");
            return Result.success(result);
        } catch (Exception e) {
            log.error("数据库测试失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("tableExists", false);
            result.put("error", e.getMessage());
            result.put("message", "数据库连接或表结构有问题");
            return Result.error(500, "数据库测试失败", result);
        }
    }
}

